﻿using Core.Formats;
using Core.ReadWriter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.Service
{
    public class WxApi : BaseService
    {
        private static readonly IDocumentFormat JsonFormat;

        static WxApi()
        {
            JsonFormat = new JsonFormat();
        }

        private string appid;
        private string secret;

        private string access_token;
        private int expires_in;
        private DateTime expires_out;
        private object expires_out_lock;

        public WxApi(string AppId, string Secret)
        {
            expires_out_lock = new object();
            appid = AppId;
            secret = Secret;
        }

        /// <summary>
        /// 获得微信 AccessToken
        /// </summary>
        public string AccessToken
        {
            get
            {
                if (DateTime.Now >= expires_out)
                {
                    lock (expires_out_lock)
                    {
                        if (DateTime.Now >= expires_out)
                        {
                            var ResultText = GetRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);

                            var Result = new Dictionary<string, object>();

                            var ResultWriter = BaseReadWriter.Create(Result);

                            JsonFormat.Decode(ResultText, ResultWriter);

                            object ErrCode;

                            if (Result.TryGetValue("errcode", out ErrCode))
                            {
                                if (Convert.ToInt32(ErrCode) != 0)
                                {
                                    object ErrMsg;

                                    Result.TryGetValue("errmsg", out ErrMsg);

                                    throw new Exception("获得 AccessToken 失败，错误码：" + ErrCode + "，错误信息：" + ErrMsg);
                                }
                            }

                            access_token = Convert.ToString(Result["access_token"]);
                            expires_in = Convert.ToInt32(Result["expires_in"]);
                            expires_out = DateTime.Now.AddSeconds(expires_in);
                        }
                    }
                }

                return access_token;
            }
        }

        /// <summary>
        /// 获得微信用户信息
        /// </summary>
        /// <param name="OpenId">用户 OpenId</param>
        /// <param name="Lang">国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语，可空</param>
        /// <returns>返回微信用户信息</returns>
        public UserInfo GetUserInfo(string OpenId, string Lang = null)
        {
            string Url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + AccessToken + "&openid=" + OpenId;

            if (Lang != null)
            {
                Url = Url + "&lang=" + Lang;
            }

            var ResultText = GetRequest(Url);

            var Result = new UserInfo();

            var ResultWriter = ObjectReadWriter.Create(Result);

            Console.WriteLine(ResultText);

            JsonFormat.Decode(ResultText, ResultWriter);

            if (Result.errcode != 0)
            {
                throw new Exception("获得用户信息失败，错误码：" + Result.errcode + "，错误信息：" + Result.errmsg);
            }

            return Result;
        }

        public class ErrorInfo
        {
            /// <summary>
            /// 错误码
            /// </summary>
            public int errcode { get; set; }
            /// <summary>
            /// 错误说明
            /// </summary>
            public string errmsg { get; set; }
        }

        public class UserInfo : ErrorInfo
        {
            /// <summary>
            /// 用户是否订阅该公众号标识，值为0时，代表此用户没有关注该公众号，拉取不到其余信息。
            /// </summary>
            public int subscribe { get; set; }
            /// <summary>
            /// 用户的标识，对当前公众号唯一
            /// </summary>
            public string openid { get; set; }
            /// <summary>
            /// 用户的昵称
            /// </summary>
            public string nickname { get; set; }
            /// <summary>
            /// 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
            /// </summary>
            public int? sex { get; set; }
            /// <summary>
            /// 用户的语言，简体中文为zh_CN
            /// </summary>
            public string language { get; set; }
            /// <summary>
            /// 用户所在城市
            /// </summary>
            public string city { get; set; }
            /// <summary>
            /// 用户所在国家
            /// </summary>
            public string province { get; set; }
            /// <summary>
            /// 用户所在省份
            /// </summary>
            public string country { get; set; }
            /// <summary>
            /// 用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空。若用户更换头像，原有头像URL将失效。
            /// </summary>
            public string headimgurl { get; set; }
            /// <summary>
            /// 用户关注时间，为时间戳。如果用户曾多次关注，则取最后关注时间
            /// </summary>
            public long subscribe_time { get; set; }
            /// <summary>
            /// 只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
            /// </summary>
            public string unionid { get; set; }
            /// <summary>
            /// 公众号运营者对粉丝的备注，公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
            /// </summary>
            public string remark { get; set; }
            /// <summary>
            /// 用户所在的分组ID（兼容旧的用户分组接口）
            /// </summary>
            public int? groupid { get; set; }
            /// <summary>
            /// 用户被打上的标签ID列表
            /// </summary>
            public int[] tagid_list { get; set; }
        }
    }
}